<?php
namespace App\Lib\Util;

use App\Lib\FileService\FastDFS;

class LargeFileUploadHelper
{
    public function doMergeThunkFile($fileGuid)
    {
        $fileDir = storage_path().'/upload/'.$fileGuid.'/';

        if (file_exists($fileDir)) {
            $handler = opendir($fileDir);
            
            $fileThunks = [];
    
            while( ($filename = readdir($handler)) !== false ) {
                if($filename != '.' && $filename != '..'){
                    if ($filename != 'menifest.dat') {
                        $fileThunks[] = intval($filename);
                    }
                }
            }
            
            closedir($handler);
    
            asort($fileThunks);
    
            $fileCount = count($fileThunks);
    
            $fileOriginName = @file_get_contents($fileDir.'menifest.dat');
            
            if (file_exists($fileDir.$fileOriginName)) {
                unlink($fileDir.$fileOriginName);
            }
    
            $fdfs = new FastDFS();
            
            $fileIds = [];

            for ($i=0; $i<$fileCount; $i++) {
                $thunkfileName = $fileDir.$fileThunks[$i];
                $fileResult = $fdfs->saveFile($thunkfileName);
                
                if ($fileResult['status'] === 0) {

                    $fileId = $fileResult['group'].'/'.$fileResult['fileName'];

                    array_push($fileIds, [
                        'fileKey' => $fileThunks[$i],
                        'fileName' => $fileId
                    ]);

                    $data = @file_get_contents($thunkfileName);
                    
                    @file_put_contents($fileDir.$fileOriginName, $data, FILE_APPEND);
                } else {
                    return ['result' => false];
                }
            }

            return [
                'result' => true,
                'fileIds' => $fileIds,
                'md5' => md5_file($fileDir.$fileOriginName),
                'fileOriginName' => $fileOriginName
            ];
        }

        return ['result' => false];
    }

    public function releaseSpace($fileGuid)
    {
        $fileDir = storage_path().'/upload/'.$fileGuid.'/';

        if (file_exists($fileDir)) {
            $handler = opendir($fileDir);
            
            $fileThunks = [];
    
            while( ($filename = readdir($handler)) !== false ) {
                if($filename != '.' && $filename != '..'){
                    unlink($fileDir.$filename);
                }
            }
            
            closedir($handler);

            rmdir($fileDir);
        }
    }
}